package com.cskaoyan.shopping.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.ICartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * /shopping/carts	/shopping/carts	/shopping/carts
 *
 * @author : Caspar
 * @since : 2022.07.09 09:24
 */
@RestController
public class ShoppingCartsController {

    @Autowired
    ICartService cartService;

    /**
     * 增加商品到购物车
     *
     * @param request
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author: Caspar CXC
     * @since 2022/07/09 11:02
     */
    @PostMapping("/shopping/carts")
    public ResponseData addItemToCart(@RequestBody AddCartRequest request) {

        AddCartResponse response = cartService.addToCart(request);
        if (response.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil().setData(ShoppingRetCode.SUCCESS.getMessage());
        }

        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 获得购物车列表，购物车的内容存在于redis当中
     *
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author: Caspar CXC
     * @since 2022/07/09 9:28
     */
    @GetMapping("/shopping/carts")
    public ResponseData getCartList(HttpServletRequest servletRequest) {

        CartListByIdRequest request = new CartListByIdRequest();

        // 获取用户信息
        String userInfo = servletRequest.getHeader("user_info");
        JSONObject jsonObject = JSON.parseObject(userInfo);

        // 将用户id封装到request当中
        long uid = Long.parseLong(jsonObject.get("uid").toString());
        request.setUserId(uid);

        CartListByIdResponse response = cartService.getCartListById(request);
        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil().setData(response.getCartProductDtos());
        }

        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 更新购物车
     *
     * @param request
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author: Caspar CXC
     * @since 2022/07/09 14:28
     */
    @PutMapping("/shopping/carts")
    public ResponseData updateCartNum(@RequestBody UpdateCartNumRequest request) {

        UpdateCartNumResponse response = cartService.updateCartNum(request);
        if (ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())) {

            return new ResponseUtil().setData(ShoppingRetCode.SUCCESS.getMessage());
        }

        return new ResponseUtil().setErrorMsg(response.getMsg());
    }
}
